//
//  OAuthViewController.swift
//  weibo
//
//  Created by sanya on 15/6/25.
//  Copyright © 2015年 sanya. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
class OAuthViewController: UIViewController,UIWebViewDelegate {

    // 0.定义常量
    private let WB_Client_ID = "3319557958"
    private let WB_Redirect_URI = "http://baidu.com"
    private let WB_App_Secret = "1e12370e79e0c24c1a4100d9e55383ac"
    // 1.webview 加载授权页
    var webView:UIWebView?
    override func loadView() {
        
        webView = UIWebView()
        webView?.delegate = self
        
        // 替换根控制器
        view = webView
        // 设置nav的信息
        title = "新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
    }
    /// 关闭当前控制器
    func close(){
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    override func viewDidLoad() {
        // 加载授权页
        loadAuthPage()
        
    }
    /// 加载授权页
    private func loadAuthPage(){
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_Client_ID)&redirect_uri=\(WB_Redirect_URI)"
        
        let url = NSURL(string: urlString)!
        webView?.loadRequest(NSURLRequest(URL: url))
    
    }
    // MARK: - UIWebViewDelegate
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        // 0. 完整的url字符串
        let urlString = request.URL!.absoluteString
//        print(urlString)
        // 1.如果不是回调的url,就继续加载
        if !urlString.hasPrefix(WB_Redirect_URI){
//            print("不是新浪")
            return true
        }
        // 2.如果是需要的回调地址，根据返回url的内容，判断是否有授权码
        // 获取请求url中的查询字符串（？之后的）
        let query = request.URL!.query!
        let codeStr = "code="
        // 判断是否含有code=
        if query.hasPrefix(codeStr){
            // 含有code=
            let code = query.substringFromIndex(advance(codeStr.endIndex, 0))
            loadAcessToken(code)
        }else{
        
            print("取消授权")
            close()
        }
        
        return false
    }
    /// 使用授权码加载Token
    private func loadAcessToken(code:String){
        // 1.请求的url
        let urlString = "oauth2/access_token"
        // 2.请求的参数
        let params = [
            "client_id":WB_Client_ID,
            "client_secret":WB_App_Secret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":WB_Redirect_URI
        ]
//        let a = UserAccount(dict: ["a":"b"])
//        a.loadUserInfo { (accout, error) -> () in
//            
//        }
        // 3.发起网络请求
        NetworkTools.shareNetworkTools().POST(urlString, parameters: params, success: { (_, json) -> Void in
            // 成功回调
            
            UserAccount(dict: json as! [String : AnyObject]).loadUserInfo { (accout, error) -> () in
                // 判断账户信息是否正确
                if accout != nil {
                    
                    sharedUserAccount = accout
                    NSNotificationCenter.defaultCenter().postNotificationName(SYSwitchRootVCNotification, object: false)
                    
                    return
                }
                print(error)
                SVProgressHUD.showInfoWithStatus("网络不给力")
            }
            
            }) { (_, error) -> Void in
                // 失败回调
                print(error)
                SVProgressHUD.showInfoWithStatus("网络不给力")
        }
  
    
    }
    
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showInfoWithStatus("正在拼命加载中.....")
        
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    

}
